package com.gcloud.mesh.asset.timer;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.gcloud.mesh.asset.service.IAssetService;
import com.gcloud.mesh.header.enums.MonitorMeter;
import com.gcloud.mesh.header.msg.asset.ListDeviceMsg;
import com.gcloud.mesh.header.msg.asset.UpdateNodeMsg;
import com.gcloud.mesh.header.vo.asset.DeviceItemVo;
import com.gcloud.mesh.monitor.service.StatisticsCheatService;
import com.gcloud.mesh.monitor.service.StatisticsService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class ServerEnergyConversionTimer {

	@Autowired
	private IAssetService assetService;

	@Autowired
	private StatisticsService statisticsService;
	
	@Autowired
    private StatisticsCheatService statisticsCheatService;

	@Scheduled(fixedDelay = 1000 * 60)
	public void work() {

		log.info("[ServerEnergyConversion] 计算服务器能效比开始 START");

		ListDeviceMsg msg = new ListDeviceMsg();
		msg.setType(6);
		List<DeviceItemVo> nodes = assetService.listDevice(msg);

		for (DeviceItemVo node : nodes) {
			String cpuUtilStr = null;
			String powerStr = statisticsCheatService.latestSample(MonitorMeter.SERVER_POWER.getMeter(), node.getId());
			String cpuFrequencyStr = statisticsCheatService.latestSample(MonitorMeter.SERVER_CPU_FREQUENCY.getMeter(),
					node.getId());
			if (statisticsCheatService.latestSamples(MonitorMeter.SERVER_CPU_UTIL.getMeter(), node.getId()).size() > 0) {
				cpuUtilStr = statisticsCheatService.latestSamples(MonitorMeter.SERVER_CPU_UTIL.getMeter(), node.getId())
						.get(0).getVolume().toString();
			}
			if(StringUtils.isNotBlank(powerStr) && StringUtils.isNotBlank(cpuUtilStr) && StringUtils.isNotBlank(cpuFrequencyStr)) {
//				if (!powerStr.isEmpty() && !cpuUtilStr.isEmpty() && !cpuFrequencyStr.isEmpty()) {
				Double power = Double.parseDouble(powerStr);
				Double cpuUtil = Double.parseDouble(cpuUtilStr) / 100;
				Double cpuFrequency = Double.parseDouble(cpuFrequencyStr) * 1024;

				Float energyEfficiencyRatio = (float) (power / (cpuUtil * cpuFrequency));

				if(energyEfficiencyRatio > 1 || energyEfficiencyRatio <= 0){
					statisticsCheatService.clearAndInitData(MonitorMeter.SERVER_POWER.getMeter(), node.getId());
					statisticsCheatService.clearAndInitData(MonitorMeter.SERVER_CPU_FREQUENCY.getMeter(), node.getId());
					statisticsCheatService.clearAndInitData(MonitorMeter.SERVER_CPU_UTIL.getMeter(), node.getId());
					continue;
				}
				UpdateNodeMsg updateNodeMsg = new UpdateNodeMsg();
				updateNodeMsg.setId(node.getId());
				updateNodeMsg.setEnergyEfficiencyRatio(energyEfficiencyRatio);
				assetService.updateNode(updateNodeMsg, "");
//				}
			}
			
		}

		log.info("[ServerEnergyConversion] 计算服务器能效比结束 END");
	}
}
